package com.example.demos.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@ResponseBody
public class LoginController {
    @RequestMapping("/login1")
    public String login1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        String userName = (String)request.getAttribute("userName");
        String password = (String) request.getAttribute("password");
        if(userName == null || password == null || "".equals(userName) || "".equals(password)){
            return "输入非法";
        }
        if("root".equals(userName) && "root".equals(password)){
            return "ok";
        }
        return "密码或用户输入错误";
    }

    @RequestMapping("/login2")
    public boolean login2(String userName, String password, HttpSession session){
       if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
           return false;
       }
       if("root".equals(userName) && "root".equals(password)){
           session.setAttribute("userName", userName);
           return true;
       }
       return false;

    }

    @RequestMapping("/getUserName")
    public String returnUserName(HttpSession session){
        String userName = (String) session.getAttribute("userName");
        if(StringUtils.hasLength(userName)){
            return userName;
        }
        return "";
    }
}
